import axios from 'axios'

let http = axios.create({
	timeout: 10000,
	baseURL: '/api',
	headers: {
		'Content-Type': 'application/json'
	}
});

http.interceptors.request.use(req => {
	let token = sessionStorage.getItem('token');
	token && (req.headers['token'] = `Bearer ${token}`);
	return req
}, error => Promise.reject(error))
//响应后干什么
http.interceptors.response.use(resp => {
	resp.data.token && sessionStorage.setItem('token', resp.data.token)
	return resp
}, error => {
	let _resp = error.response
	switch (_resp.status) {
		case 401:
			//把本地的token清除  跳转到login
			sessionStorage.removeItem('token')
			sessionStorage.removeItem('userName')
			sessionStorage.removeItem('type')
			alert('身份已过期,请重新登录')
			// return router.push('/login')
	}
	return Promise.reject(error.response.data)
});

export default http
